package com.mine.frame.common.base

import com.mine.frame.common.net.BaseRequest
import com.mine.frame.common.net.entity.RespondBean
import com.mine.frame.common.net.listener.ResponseListener
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers

/**
 * company 广东玛格家居有限公司
 * @author smoker
 * @Date 2021/11/12
 * Description:
 */
abstract class BaseModel {

    /**
     * API
     * 请求
     */
    protected val api by lazy { BaseRequest.instant.apiService }

    /**
     * 封装的请求
     * @param tag 取消请求的target
     * @param request 请求的API
     */
    protected fun <M> request(tag:Any, request: Observable<RespondBean<M>>, responseListener: ResponseListener<M>) {
        request.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe {
                responseListener.onStart(tag,it)
            }
            .doOnNext {
                when(it.code){
                    200 , 201 ->{
                        responseListener.onSuccess(it)
                    }
                    else ->{
                        responseListener.onError(Throwable(it.msg))
                    }
                }
            }
            .doOnError {
                responseListener.onError(it)
            }
            .doOnComplete {
                responseListener.onFinish()
            }
            .subscribe()
    }
}